<?php

namespace addons\booking\controller;

use addons\booking\model\Store as StoreModel;
use think\Session;
use app\common\model\booking\store\Category;
use addons\booking\model\Coupon;
use addons\booking\model\UserCoupon;
use addons\booking\model\CouponCondition;
use addons\booking\library\IntCode;
use addons\booking\model\House;
use addons\booking\model\Config;
use addons\booking\model\Comment;

class Store extends Base
{
    protected $noNeedLogin = ['indexStoreList','categoryList','storeList', 'detail', 'defaultStore', 'cutStore'];

    /**
     * 门店列表
     */
    public function storeList()
    {
        $this->success('', StoreModel::tableList($this->request->param(),$this->auth->id));
    }
     /**
     * 分类列表
     */
    public function categoryList()
    {
        $this->success('', Category::getList());
    }
     /**
     * 首页推荐门店列表
     */
    public function indexStoreList()
    {
        $this->success('', StoreModel::indexTableList($this->request->param(),$this->auth->id));
    }


    /**
     * 切换
     */
    public function cutStore()
    {
        $store_id = $this->request->post('store_id');
        if (!$store_id) {
            $this->error('参数错误');
        }
        $data = StoreModel::getDetail($store_id);
        if (!$data) {
            $this->error('未找到相关门店信息');
        }
        Session::set('store_id', $store_id);
        $this->success('切换成功！');
    }

    /**
     * 默认门店或手动切换的门店
     */
    public function defaultStore()
    {
        $id = Session::get('store_id');
        $latitude = $this->request->param('latitude');
        $longitude = $this->request->param('longitude');
        $PI = M_PI;
        $data = null;
        $fields = "id,name,images,phone,latitude,longitude,address,(2 * 6378.137 * ASIN(SQRT(POW(SIN($PI*({$latitude}-latitude)/360),2)+COS($PI*{$latitude}/180)* COS(latitude * $PI/180)*POW(SIN($PI*({$longitude}-longitude)/360),2)))) as distance";
        if ($id) {
            $data = StoreModel::field('id,name,images,phone,latitude,longitude,address')->where('status', 'normal')->where('id', $id)->find();
        } elseif ($latitude && $longitude) {
            $data = StoreModel::field($fields)->order('distance asc')->where('status', 'normal')->find();
        }
        if (!$data) {
            $data = StoreModel::field('id,name,images,phone,latitude,longitude,address')->where('status', 'normal')->where('is_default', 1)->find();
        }
        if (!$data) {
            $this->error('未找到相关门店信息');
        }
        $data->is_more = (StoreModel::count()) > 1;
        $this->success('', $data);
    }

    /**
     * 详情
     */
    public function detail()
    {
        $id = $this->request->param('id/d');
        if (empty($id)) {
            $this->error('参数缺失');
        }
        $calendar = $this->request->param('calendar');
        if (!empty($calendar)) {
            $calendar = explode('/', $calendar);
            if (count($calendar) == 2) { //时间范围
                $time = strtotime($calendar[1]);
                if ($time < time()) {
                    $this->error('不能查询过去的房间状态');
                }
            }
        }
        $data = StoreModel::getDetail($id,$this->request->param());
        if($data && $data["avatar"]){
            $data["avatar"]= cdnurl($data['avatar'], true);
        }
        if($data&&$data['house']){
             //房间
            $house_ids = House::alias("h")
                        ->where(['h.store_id'=>$id])
                        ->column("id");
            if($house_ids){
                //评价
                $avg_grade = Comment::where('type=0 and source_id in('.implode(",",$house_ids).')')->avg("grade");//
                $data['avg_grade'] = $avg_grade;
                $data['comment'] = Comment::where('type=0 and source_id in('.implode(",",$house_ids).')')->orderRaw("grade desc,rand()")->value('comment');
                $data['comment_count'] = Comment::where('type=0 and source_id in('.implode(",",$house_ids).')')->count();
                $commentList = Comment::with([
                                        'User'   => function ($query) {
                                            $query->field('id,nickname,avatar');
                                        }])->where('type=0 and source_id in('.implode(",",$house_ids).')')->select();
                    foreach ($commentList as &$item) {
                        if ($item['user']) {
                            $item['user']['avatar'] = cdnurl($item['user']['avatar'], true);
                        }
                    }
                    unset($item);
                $data['comment_list'] = $commentList;
            }
            
             //房间
            $houseInfo = House::alias("h")
                        ->join('booking_config c', 'FIND_IN_SET(c.id,h.tag_config_ids)', 'LEFT')
                        ->where(['h.status'=>'up','h.store_id'=>$id])
                        // ->field("h.id,h.market_price,h.price,GROUP_CONCAT(c.name ORDER BY FIND_IN_SET(c.id, h.tag_config_ids)) tag_names")
                        ->order("h.weigh desc,h.price desc")
                        ->find();
             if ($houseInfo) {
                $groupName = ['facility' => [], 'tag' => []];
                $tagConfigIds = explode(',', $houseInfo['tag_config_ids']);
                $facilityConfigIds = explode(',', $houseInfo['facility_config_ids']);
                $configIds = array_merge($tagConfigIds, $facilityConfigIds);
                $configIds = array_filter($configIds);
                if ($configIds) {
                    $configData = Config::where('id', 'in', $configIds)->orderRaw("FIELD(`id`, " . implode(',', $configIds) . ")")->column('id,name');
                    foreach ($tagConfigIds as $index => $tagConfigId) {
                        if (isset($configData[$tagConfigId])) {
                            $groupName['tag'][] = $configData[$tagConfigId];
                        }
                    }
                    foreach ($facilityConfigIds as $index => $facilityConfigId) {
                        if (isset($configData[$facilityConfigId])) {
                            $groupName['facility'][] = $configData[$facilityConfigId];
                        }
                    }
                }
                $data['group_names'] = $groupName;
            }
            $couponList = [];
             foreach ($data['house'] as &$val){
                 $conditions = CouponCondition::getHouseCondition($val['id'], $id);
                    $sql = "condition_ids IS NULL OR condition_ids=''";
                    foreach ($conditions as $key => $item) {
                        $item['id'] = (int)$item['id'];
                        $sql .= " OR FIND_IN_SET('{$item['id']}',condition_ids)";
                    }
                    $list = Coupon::field('id,name,result,result_data,alone_num,receive_times,mode,createtime,received_num,give_num')->where($sql)->select();
                    //已经登录，渲染已领的优惠券
                    $coupon_ids = [];
                    if ($this->auth->isLogin()) {
                        $coupon_ids = UserCoupon::where('user_id', $this->auth->id)->column('coupon_id');
                    }
                    $newList = [];
                    foreach ($list as $item) {
                        Coupon::render($item, $coupon_ids);
                        $item->id = IntCode::encode($item->id);
                        $newList[] = $item;
                    }
                    unset($list);
                    if($newList){
                       array_push($couponList,$newList); 
                    }
                    $val['coupon'] = $newList?$newList[0]:[];
             }
             $data['coupon_list'] = $couponList;
        }
        if (!$data) {
            $this->error('未找到相关门店信息');
        }
        $this->success('', $data);
    }
     /**
     * info
     */
    public function info()
    {
        $id = $this->request->param('id/d');
        if (empty($id)) {
            $this->error('参数缺失');
        }
    
        $data = StoreModel::getInfo($id);
      
        if (!$data) {
            $this->error('未找到相关门店信息');
        }
        $this->success('', $data);
    }
}
